package cn.deathlock;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DeathLockTwo {
    public static void main(String[] args) {
        Chopstick c1=new Chopstick("1");
        Chopstick c2=new Chopstick("2");
        Chopstick c3=new Chopstick("3");
        Chopstick c4=new Chopstick("4");
        Chopstick c5=new Chopstick("5");
        new Philosopher("1",c1,c2).start();
        new Philosopher("2",c2,c3).start();
        new Philosopher("3",c3,c4).start();
        new Philosopher("4",c4,c5).start();
        new Philosopher("5",c5,c1).start();

    }
    static class Philosopher extends Thread{
        private Chopstick left;//左手筷子
        private Chopstick right;//右手筷子
        public Philosopher(String name,Chopstick left,Chopstick right){
             super(name);
            this.left=left;
            this.right=right;
        }

        @Override
        public void run() {
            super.run();
            while (true){ //不断尝试
                synchronized (left){
                    synchronized (right){
                        //同时获得筷子 吃饭
                        log.info("eating.......");
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    static class Chopstick{
     String name;
        public Chopstick(String name) {
            this.name = name;
        }
    }
}
